package com.CmJava.service;

import com.CmJava.entity.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //dubbo远程调用
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userService.getUser(userName);

        if (user != null) {
            List<GrantedAuthority> authorities = null;
            if (user.getAuthentication().equals("admin")) {
                authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_admin");
            } else {
                authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("user");
            }
            String password = bCryptPasswordEncoder.encode(user.getUserPassword());
            return new org.springframework.security.core.userdetails.User(user.getUserName(), password, authorities);
        } else {
            throw new UsernameNotFoundException("用户名不存在");
        }
    }
}
